爱客仕-前端团队博客园

Nodejs查漏补缺-Standard I/O

在这里记录下nodejs各种小细节

ch2 Standard I/O

首先讲一下什么叫做Standard I/O——标准输入输出流

Standard streams
Standard streams come in three flavors: stdin, stdout, and stderr. In Unix terminals,
these are referred to with numbers. 0 is used for standard input, 1 is standard output,
and 2 is standard error.
The same applies to Windows: running a program from the command prompt and add-
ing 2> errors-file.log will send the error messages to errors-file.log , just
like Unix.

标准流
标准流有三种类型 stdin,stdout,stderr,在类unix终端中,被引用为数字
0 - 标准输入
1 - 标准输入
2 - 标准错误
这也同样被运用在windows中:在命令行运行一个程序并在最后加上 2>err.log
将会把错误信息发送至err.log文件下(当然unix like系统同样如此)

那么这玩意有什么用呢?

nodejs提供了三个对象process.stdin, process.stdout, process.stderr
可以轻松的获取到标准输入输出

example:

1
2
3
4
5
6
7
8
9
10
// std.js
'use strict'
process.stdin.resume() //告诉node开始接收标准输入
process.stdin.setEncoding('utf-8')
process.stdin.on('data', (data) => {
process.stdout.write(data.toUpperCase()); // 流的读取都是分段的
})


run with:

1
cat file.txt | node std.js | grep FOO

利用unix管道,可以将流pipe进node程序,node程序将读入的文本转成大写,再pipe出去
流会被下一个程序接收,如果是最后一个,则会打印至控制台
或者可以使用1> log.txt将标准输出 pipe进文件

1
cat file.txt | node std.js | grep FOO 1> log.txt